package com.imgo.max.fans.service;

import com.imgo.max.artist.constant.FansConstant;
import com.imgo.max.artist.service.FansCacheService;
import com.imgo.max.cache.util.CacheCommonManager;
import com.imgo.max.common.dto.APIException;
import com.imgo.max.common.dto.ResultDO;
import com.imgo.max.common.log.CustomLogger;
import com.imgo.max.common.log.CustomLoggerFactory;
import com.imgo.max.common.result.FansResultCodeEnum;
import com.imgo.max.common.result.ModuleResultCode;
import com.imgo.max.common.util.LoggerUtils;
import com.imgo.max.common.util.ValidatorUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 粉丝缓存接口实现类
 * Created by darren.dai on 12/14/16.
 */
@Service("fansCacheService")
public class FansCacheServiceImpl implements FansCacheService {
    private static final CustomLogger logger = CustomLoggerFactory.getLogger(FansCacheServiceImpl.class);

    @Autowired
    CacheCommonManager cacheCommonManager;

    /**
     * 查询用户是否关注指定艺人列表中的艺人
     *
     * @param uid
     * @param artistUidList
     * @return
     */
    @Override
    public ResultDO<Map<String, Boolean>> isFollowed(String uid, List<String> artistUidList) {
        ResultDO<Map<String, Boolean>> resultDO = ResultDO.buildResult();
        try {
            if (!ValidatorUtils.isValidUid(uid) || CollectionUtils.isEmpty(artistUidList)) {
                throw new APIException(FansResultCodeEnum.PARAM_IS_EMPTY_ERROR);
            }
            Map<String, Boolean> resultMap = new HashMap<>();
            // 获取Redis zset 中的 score，member不存在返回的是null
            String key = getFollowedReidsKey(uid);
            List<Object> scoreList = cacheCommonManager.getZSetScores(key, artistUidList, CacheCommonManager.RedisTemplateEnum.STRINGSERIALIZER);

            // 遍历返回结果
            int size = artistUidList.size();
            String artistUid;
            Object tmpScore;
            for (int i = 0; i < size; i++) {
                artistUid = artistUidList.get(i);
                tmpScore = scoreList.get(i);
                boolean tmpB = true;
                if (tmpScore == null) {
                    tmpB = false;
                }
                resultMap.put(artistUid, tmpB);
            }
            resultDO.setModule(resultMap);
        } catch (Exception e) {
            LoggerUtils.errorAndResultDO(logger, e, ModuleResultCode.FANS, resultDO, uid, artistUidList);
        }
        return resultDO;
    }

    /**
     * 查询用户与艺人的关注关系
     *
     * @param uid
     * @param artistUid
     * @return
     */
    @Override
    public ResultDO<Boolean> isFollowed(String uid, String artistUid) {
        ResultDO<Boolean> resultDO = ResultDO.buildResult();
        try {
            if (!ValidatorUtils.isValidUid(uid) || !ValidatorUtils.isValidUid(artistUid)) {
                throw new APIException(FansResultCodeEnum.PARAM_IS_EMPTY_ERROR);
            }
            String key = getFollowedReidsKey(uid);
            Double score = cacheCommonManager.getZsetScore(key, artistUid, CacheCommonManager.RedisTemplateEnum.STRINGSERIALIZER);
            boolean result = true;
            if (score == null) {
                result = false;
            }
            resultDO.setModule(result);
        } catch (Exception e) {
            LoggerUtils.errorAndResultDO(logger, e, ModuleResultCode.FANS, resultDO, uid, artistUid);
        }
        return resultDO;
    }


    /**
     * 用户关注Redis key
     * @param uid
     * @return
     */
    private String getFollowedReidsKey(String uid) {
        return FansConstant.REDIS_USER_FOLLOWING_ARTIST_ZSET_PREFIX + uid;
    }
}
